package com.kaifamiao.date;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;

/**
 * 1、java.util.Date 实现了 java.lang.Comparable 接口，因此支持自然排序
 * 2、如果需要实现自定义排序，可以通过 java.util.Comparator 来实现
 */
public class DateTest3 {

	public static void main(String[] args) {
		
		final long day = 1000L * 60 * 60 * 24 ;
		final long ms = System.currentTimeMillis() ;
		
		Date[] dates = {
				new Date( ms ),
				new Date() ,
				new Date( ms - day ),
				new Date( ms - day * 2 ) ,
				new Date( ms + day * 1 ) ,
				new Date( ms - day * 365 )
		};
		
		for( int i = 0 , n = dates.length ; i < n ; i++ ) {
			Date date = dates[ i ];
			System.out.println( date );
		}
		
		// 使用 Arrays.sort 对 Date 数组排序
		Arrays.sort( dates ); // Comparable
		
		System.out.println( "- - ".repeat( 10 ) );
		
		for( int i = 0 , n = dates.length ; i < n ; i++ ) {
			Date date = dates[ i ];
			System.out.println( date );
		}
		
		System.out.println( "- - ".repeat( 10 ) );
		
		Comparator<Date> comparator = new Comparator<Date>() {
			@Override
			public int compare(Date first, Date second) {
				int result = 0 ; 
				if( first.before(second) ) {
					result = -1 ;
				} 
				if( first.equals( second ) ) {
					result = 0 ;
				}
				if( first.after( second ) ) {
					result = 1 ;
				}
				return -result ;
			}
		} ;
		
		Arrays.sort( dates , comparator );
		
		for( int i = 0 , n = dates.length ; i < n ; i++ ) {
			Date date = dates[ i ];
			System.out.println( date );
		}

	}

}
